package com.huiw.archives.common.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.huiw.archives.common.annotation.WebLoginRequired;
import com.huiw.archives.common.utils.AjaxUtil;

/**
 * @author YC
 *
 */
public class LoginInterceptor implements HandlerInterceptor {

	private static Log logger = LogFactory.getLog(LoginInterceptor.class);

	public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
			Object handler) throws Exception {

		if (logger.isDebugEnabled()) {
			logger.debug("拦截器启动");
		}
		/*
		 * 判断是否为 HandlerMethod.class 如果不是说明当前请求并不是 SpringMVC 管理，
		 * 如果不是再自行根据业务做响应操作，这里直接返回 true
		 */
		if (HandlerMethod.class.isInstance(handler)) {
			HandlerMethod handlerMethod = (HandlerMethod) handler;

			// 判断该 handler 是否有WebLoginRequired注解
			WebLoginRequired webLoginRequired = handlerMethod.getMethod().getAnnotation(WebLoginRequired.class);

			// 如果该 handler 没有WebLoginRequired注解，判断所属Controller 是否包含注解
			if (null == webLoginRequired) {
				webLoginRequired = handlerMethod.getBeanType().getAnnotation(WebLoginRequired.class);
			}

			// 如果需要 WebLoginRequired 判断 session
			if (null != webLoginRequired) {
				if (httpServletRequest.getSession().getAttribute("user") == null) {
					String executeURL = webLoginRequired.value();
					if (StringUtils.isBlank(executeURL)) {
						executeURL = "/error.jsp";
					}

//					httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + executeURL);
					AjaxUtil.ajaxJSONResponse(httpServletResponse, "未登录");
					return false;
				}
			}
		}
		return true;
	}

	public void postHandle(javax.servlet.http.HttpServletRequest httpServletRequest,
			javax.servlet.http.HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView)
			throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("postHandler");
		}
	}

	public void afterCompletion(javax.servlet.http.HttpServletRequest httpServletRequest,
			javax.servlet.http.HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("afterCompletion");
		}
	}
}
